import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { printerApi, PrinterFormData } from '../../services/printerApi';
import './printer-add.css';

const PrinterAdd: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [formData, setFormData] = useState<PrinterFormData>({
    name: '',
    ip: '',
    port: 631,  // IPP 默认端口
    protocol: 'IPP',  // 改为大写
    description: ''
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    console.log('表单字段变更:', { field: name, value });
    
    setFormData(prev => ({
      ...prev,
      [name]: name === 'port' ? parseInt(value) || 0 : value
    }));
  };

  const validateForm = (): string | null => {
    if (!formData.name.trim()) return '请输入打印机名称';
    if (!formData.ip.trim()) return '请输入IP地址';
    if (!formData.port) return '请输入端口号';
    if (!formData.protocol) return '请选择协议';
    
    // IP地址格式验证 - 允许文本输入以支持USB和串口连接
    if (formData.ip !== 'USB连接' && formData.ip !== '串口连接') {
      const ipPattern = /^(\d{1,3}\.){3}\d{1,3}$/;
      if (!ipPattern.test(formData.ip)) return 'IP地址格式不正确';
    }
    
    // 端口范围验证
    if (formData.port < 1 || formData.port > 65535) return '端口号必须在1-65535之间';
    
    // 协议验证
    if (!['RAW', 'IPP'].includes(formData.protocol)) {
      return '无效的协议类型';
    }
    
    return null;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    console.log('提交表单数据:', formData);

    const validationError = validateForm();
    if (validationError) {
      console.log('表单验证失败:', validationError);
      setError(validationError);
      return;
    }

    try {
      setLoading(true);
      setError(null);
      console.log('开始添加打印机:', {
        formData,
        timestamp: new Date().toISOString()
      });

      const response = await printerApi.addPrinter(formData);
      console.log('添加打印机成功:', {
        response,
        timestamp: new Date().toISOString()
      });

      setSuccess('添加打印机成功！即将返回列表...');
      
      // 延迟导航，让用户看到成功消息
      setTimeout(() => {
        navigate('/printers');
      }, 1500);
    } catch (err: any) {
      console.error('添加打印机失败:', {
        error: err,
        message: err.message,
        response: err.response,
        data: err.response?.data,
        timestamp: new Date().toISOString()
      });

      if (err.response?.data?.message) {
        setError(err.response.data.message);
      } else if (err.message) {
        setError(`添加失败: ${err.message}`);
      } else {
        setError('添加打印机失败，请重试');
      }
    } finally {
      setLoading(false);
    }
  };

  // 渲染错误信息
  const renderError = () => {
    if (!error) return null;
    return (
      <div className="error-message">
        <span>{error}</span>
        <button className="close-btn" onClick={() => setError(null)}>×</button>
      </div>
    );
  };

  // 渲染成功信息
  const renderSuccess = () => {
    if (!success) return null;
    return (
      <div className="success-message">
        <span>{success}</span>
      </div>
    );
  };

  return (
    <div className="printer-add-container">
      <div className="printer-add-header">
        <h1>添加打印机</h1>
        <button className="btn btn-text" onClick={() => navigate('/printers')}>
          <i className="fas fa-arrow-left"></i>
          返回列表
        </button>
      </div>

      {renderError()}
      {renderSuccess()}

      <form className="printer-add-form" onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="name">打印机名称</label>
          <input
            type="text"
            id="name"
            name="name"
            value={formData.name}
            onChange={handleChange}
            placeholder="例如: 办公室打印机"
            disabled={loading}
            required
          />
          <div className="form-hint">输入打印机的名称，便于识别</div>
        </div>

        <div className="form-row">
          <div className="form-group">
            <label htmlFor="ip">连接方式</label>
            <input
              type="text"
              id="ip"
              name="ip"
              value={formData.ip}
              onChange={handleChange}
              placeholder="IP地址、USB连接或串口连接"
              disabled={loading}
              required
            />
            <div className="form-hint">
              输入IP地址或选择连接类型 (如: 192.168.1.100, USB连接, 串口连接)
            </div>
          </div>

          <div className="form-group">
            <label htmlFor="port">端口</label>
            <input
              type="number"
              id="port"
              name="port"
              value={formData.port}
              onChange={handleChange}
              min="1"
              max="65535"
              disabled={loading}
              required
            />
            <div className="form-hint">
              IPP默认端口: 631, RAW默认端口: 9100
            </div>
          </div>
        </div>

        <div className="form-group">
          <label htmlFor="protocol">协议</label>
          <select
            id="protocol"
            name="protocol"
            value={formData.protocol}
            onChange={handleChange}
            disabled={loading}
            required
          >
            <option value="IPP">IPP</option>
            <option value="RAW">RAW</option>
          </select>
          <div className="form-hint">
            IPP适用于现代打印机，支持更多功能；RAW适用于老式打印机，更简单稳定
          </div>
        </div>

        <div className="form-group">
          <label htmlFor="description">描述（可选）</label>
          <textarea
            id="description"
            name="description"
            value={formData.description}
            onChange={handleChange}
            placeholder="添加打印机描述信息"
            disabled={loading}
            rows={3}
          />
        </div>

        <div className="form-actions">
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate('/printers')}
            disabled={loading}
          >
            取消
          </button>
          <button
            type="submit"
            className="btn btn-primary"
            disabled={loading}
          >
            {loading ? '添加中...' : '添加打印机'}
          </button>
        </div>
      </form>
    </div>
  );
};

export default PrinterAdd; 